//
//  MWMineCollectionController.m
//  XiRan-iOS
//
//  Created by Richfit on 2019/10/30.
//  Copyright © 2019 Wood. All rights reserved.
//

#import "MWMineCollectionController.h"
#import "MWGoodsDetailsController.h"
#import "MWGoodsCell.h"

@interface MWMineCollectionController () <UICollectionViewDataSource, UICollectionViewDelegate>

@property (strong, nonatomic) MJRefreshNormalHeader *refreshHeader;
@property (strong, nonatomic) MJRefreshAutoNormalFooter *refreshFooter;
@property (strong, nonatomic) UICollectionView *collectionView;

@property(strong, nonatomic) NSMutableArray *goodsArray;

@property(nonatomic, assign) CGFloat cellHeight;

@property(nonatomic, assign) NSInteger page;
@property(nonatomic, assign) NSInteger size;
@property(nonatomic, assign) MWRequestMode requestMode;

@end

@implementation MWMineCollectionController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = [[MWConfigManager manager] objectForKey:@"goods_collect" defaultValue:@"商品收藏"];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    [_collectionView registerClass:[MWGoodsCell class] forCellWithReuseIdentifier:@"MWGoodsCell"];
    [self.view addSubview:_collectionView];
    
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    _refreshHeader = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self refreshGoods];
    }];
    _refreshHeader.stateLabel.hidden = YES;
    _collectionView.mj_header = _refreshHeader;
    
    _refreshFooter = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreGoods];
    }];
    _refreshFooter.stateLabel.hidden = YES;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [_refreshHeader beginRefreshing];
}

- (void)refreshGoods {
    _page = 1;
    _requestMode = MWRequestModeRefresh;
    [self loadCollectionWithPage:_page size:_size];
}

- (void)loadMoreGoods {
    _page++;
    _requestMode = MWRequestModeLoadMore;
    [self loadCollectionWithPage:_page size:_size];
}


#pragma mark - 收藏列表
- (void)loadCollectionWithPage:(NSInteger)page size:(NSInteger)size {
    NSString *token = [MWUserManager manager].user.token;
    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
    [paraDic setObject:token forKey:@"token"];
    [paraDic setObject:[NSString stringWithFormat:@"%ld", (long)page] forKey:@"page"];
    [paraDic setObject:[NSString stringWithFormat:@"%ld", (long)size] forKey:@"size"];
    [paraDic setObject:[MWConfigManager manager].language forKey:@"language"];
     [paraDic setObject:[MWConfigManager manager].productType forKey:@"is_material"];
    
    MWWeakSelf
    [[MWNetworkManager manager] POST:kMineCollectionUrl parameters:paraDic progress:^(NSProgress *downloadProgress) {
        
    } success:^(id responseObject) {
        NSDictionary *dic = responseObject;
        NSInteger code = [[dic objectForKey:@"code"] integerValue];
//        NSString *msg = [dic objectForKey:@"msg"];
        if (code == 1) {
            NSArray *tempArray = [MWGoods mj_objectArrayWithKeyValuesArray:[dic objectForKey:@"data"]];
            if (weakSelf.requestMode == MWRequestModeRefresh) {
                [weakSelf.collectionView.mj_header endRefreshing];
                [self.goodsArray removeAllObjects];
                
                if (tempArray.count == 10) {
                    weakSelf.collectionView.mj_footer = weakSelf.refreshFooter;
                }
                
            } else {
                if (tempArray.count < 10) {
                    [weakSelf.collectionView.mj_footer endRefreshingWithNoMoreData];
                } else {
                    [weakSelf.collectionView.mj_footer endRefreshing];
                }
            }
            
            [weakSelf.goodsArray addObjectsFromArray:tempArray];
            weakSelf.cellHeight = [weakSelf calculateCellHeight];
            [weakSelf.collectionView reloadData];
            
        } else {
            [weakSelf.collectionView.mj_header endRefreshing];
            [weakSelf.collectionView.mj_footer endRefreshing];
        }
        
    } failure:^(NSError *error) {
        [weakSelf.collectionView.mj_header endRefreshing];
        [weakSelf.collectionView.mj_footer endRefreshing];
    }];
}

- (void)handleGoodsResult:(NSDictionary *)dic {

}

#pragma mark - UICollectionViewDataSource && UICollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if ([MWConfigManager manager].isNetError) {
        self.errorTitleLabel.text = [[MWConfigManager manager] objectForKey:@"click_retry" defaultValue:@"点击重试"];
        self.errorTitleLabel.hidden = self.errorImageView.hidden = NO;
        collectionView.hidden = YES;
    } else if (!self.goodsArray.count) {
        if (self.isFirst) {
            
        } else {
        }
        self.errorTitleLabel.text = [[MWConfigManager manager] objectForKey:@"no_favorites" defaultValue:@"暂无收藏"];
        self.errorTitleLabel.hidden = self.errorImageView.hidden = NO;
        collectionView.hidden = YES;
        
    } else {
        self.errorTitleLabel.hidden = self.errorImageView.hidden = YES;
        collectionView.hidden = NO;
    }
    return self.goodsArray.count;
}

- (void)refresh {
    [super refresh];
    [self.refreshHeader beginRefreshing];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"MWGoodsCell";
    MWGoodsCell *goodCell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    [goodCell setupData:self.goodsArray[indexPath.row]];
    return goodCell;
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 12;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 20;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(16, 16, 16, 16);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeZero;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    return CGSizeZero;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake((kScreenWidth - 52) / 2, _cellHeight);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    MWGoods *goods = self.goodsArray[indexPath.row];
    MWGoodsDetailsController *controller = [[MWGoodsDetailsController alloc] init];
    controller.productId = [NSString stringWithFormat:@"%ld", goods.mid];
    [self.navigationController pushViewController:controller animated:YES];
}

#pragma mark - 计算cell 高度
- (CGFloat)calculateCellHeight {
    CGFloat imgH = 120.0f;
    CGFloat titleH = 22.0f;
    CGFloat priceH = 0;
    CGFloat attrH = 0.0f;
    
    for (MWGoods *goods in self.goodsArray) {
        if (!goods.shuxing) {
            break;
        }
        
        if (goods.price) {
            priceH = 22.0f;
        }
        
        if (attrH < goods.shuxing.count * 22) {
            attrH = goods.shuxing.count * 22;
        }
    }
    
    return imgH + 8 + titleH + priceH + attrH;
}

- (NSMutableArray *)goodsArray {
    if (!_goodsArray) {
        _goodsArray = [[NSMutableArray alloc] init];
    }
    return _goodsArray;
}


@end
